import 'dart:convert';

import 'package:flutter/material.dart';
import 'package:sml_policies/locator/locator.dart';
import 'package:webview_flutter/webview_flutter.dart';

import '../../locator/sml_policies.dart';

class CommonWebView extends StatefulWidget {
  CommonWebView({
    Key? key,
    required this.url,
    this.onScrollToBottom,
    this.onClosePop
  }) : super(key: key);

  String url;
  Function? onScrollToBottom;
  Function? onClosePop;

  @override
  State<CommonWebView> createState() => _CommonWebViewState();
}

class _CommonWebViewState extends State<CommonWebView> {

  late WebViewController _webViewCtrl;

  @override
  void initState() {
    initWebView();
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    return WebViewWidget(
      controller: _webViewCtrl
    );
  }

  initWebView() {
    _webViewCtrl = WebViewController.fromPlatformCreationParams(
        const PlatformWebViewControllerCreationParams());

    _webViewCtrl
      ..setJavaScriptMode(JavaScriptMode.unrestricted)
      ..setNavigationDelegate(NavigationDelegate(
          onProgress: (int process) async {
            debugPrint('${await _webViewCtrl.currentUrl()} process: $process');
          },
          onPageFinished: (String value) {

          }
      ))
      ..enableZoom(false)
      ..addJavaScriptChannel("FKSDKJsFramework", onMessageReceived: (JavaScriptMessage message) {
        Map<String, dynamic> msgJson = jsonDecode(message.message);
        debugPrint('msgJson: $msgJson');

        var action = msgJson['action'];
        if (action == 'scrollToBottom') {
          widget.onScrollToBottom?.call();

        } else if (action == "closePopNow") {
          if (msgJson['needClose'] == true) {
            widget.onClosePop?.call();
          }

        } else if (action == "logEventByAF") {
          locator<SmlPoliciesConfig>().logEvent(msgJson['data']['event']);
        }
      })
      ..loadRequest(Uri.parse(widget.url));
  }

}
